import React, { useState, useEffect } from 'react';
import { Modal, Button, Space, Select } from 'antd';
import userService from '@/api/services/userService';

import Cookies from 'js-cookie';
import { jwtDecode } from 'jwt-decode';
import { useUserActions, useUserInfo } from '@/store/userStore';
// import useInitialize from '@/hooks/event/use-initialize';
import { useRoleManage, useRoles } from '@/store/roleManageStore';
import { useRouter } from '@/router/hooks';

const { VITE_TOKEN: VITETOKEN } = import.meta.env;

const RoleSwitchModal = ({ open, onOk, onCancel }) => {
  const [roles, setRoles] = useState([]);
  const [selectedRole, setSelectedRole] = useState(null);

  const { setUserToken,  setUserInfo} = useUserActions();
  const { username } = useUserInfo();
  // const { isDebug } = useInitialize()
  const router = useRouter();

  useEffect(() => {
    open && userService
      .getRoles()
      .then((response) => {
        console.log(response?.roles);
        setRoles(response?.roles);
      })
      .catch((error) => {
        console.error('Failed to fetch roles:', error);
      });
  }, [open]);

  const handleRoleChange = (value) => {
    setSelectedRole(value);
    console.log(`selected ${value}`);
  };


  const updateInfo = () => {
    const token = Cookies.get(VITETOKEN)
    if (!token) {
      return
    }

    const decodedToken = jwtDecode(token);
    const mergeUser = {
      username,
      ...(decodedToken?.roles && {
        role: (() => {
          if (!Array.isArray(decodedToken.roles)) {
            return decodedToken.roles;
          } else {
            if (decodedToken.roles.length === 1) {
              return decodedToken.roles[0];
            } else {
              const role = {
                list:decodedToken.roles,
                name: decodedToken.roles.map((item) => item.name).join('/'),
                code: decodedToken.roles.map((item) => item.code),
              };
              return role;
            }
          }
        })(),
      }),
    };

    setUserInfo(mergeUser)
    setUserToken({ accessToken:token, refreshToken:token })

  }


  const handleRoleSubmit = () => {
    console.log(selectedRole)
    if (selectedRole) {
      userService.updateRoleDebug({
        id: selectedRole
      }).then(() => {
        updateInfo()

        onOk();
        
        router.push("/");
        // window.location.reload();
      }).catch((error) => {
        console.error('Failed to update role:', error);
      });
    } else {
      console.warn('No role selected');
    }
  };

  return (
    <Modal
      title={<div style={{ textAlign: 'center', width: '100%' }}>切换角色</div>}
      open={open}
      onOk={handleRoleSubmit} // 调用 handleRoleSubmit 函数
      onCancel={onCancel}
      okText="确定"
      cancelText="取消"
      closable={false}
      width={300}
      centered
      footer={
        <div style={{ textAlign: 'center' }}>
          <Space size={56}>
            <Button onClick={onCancel}>取消</Button>
            <Button type="primary" onClick={handleRoleSubmit}>确定</Button>
          </Space>
        </div>
      }
    >
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '60px'
        }}
      >
        <Select
          value={selectedRole?.id}
          style={{ 
            width: '100%',
            // border: '1px solid #6640ff',
            borderRadius: '16px'
          }}
          onChange={handleRoleChange}
          options={roles.map(role => ({ value: role?.id, label: role?.name }))}
        />
      </div>
    </Modal>
  );
};

export default RoleSwitchModal;